package com.outlook.util;

import java.util.Date;
import java.util.Locale;
import java.util.Random;

/**
 * 
 * @author watson
 *
 */
public class RandomUtil {

	public static Random random = new Random();
	private static final int DEFAULT_RANGE = 100000;
	private static final int DEFAULT_LENGTH = 10;

	public static Random getRandom() {
		return random;
	}

	public static String getRandomString() {
		return getRandomString(DEFAULT_LENGTH);
	}

	public static String getRandomString(Locale locale) {
		return getRandomString(DEFAULT_LENGTH, locale);
	}

	public static String getRandomString(int length) {
		return getRandomString(length, Locale.getDefault());
	}

	private static String getRandomString(int length, Locale locale) {
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<length; i++) {
			sb.append(getLocalRandomString(locale));
		}
		return sb.toString();
	}
	
	public static String getLocalRandomString() {
		return getLocalRandomString(Locale.getDefault());
	}
	
	public static String getLocalRandomString(Locale locale) {
		if(locale.equals(Locale.CHINA)) {
			return getChinese();
		} else {
			return getEnglish();
		}
	}

	public static String getEnglish() {
		final int randomInt = 65 + random.nextInt(57);
		char[] chars = new char[1];
		chars[0] = (char)(randomInt);
		return new String(chars);
	}

	public static String getEnglish(int length) {
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<length; i++) {
			sb.append(getEnglish());
		}
		return sb.toString();
	}
	
	public static String getEnglishMixNumber() {
		return null;
	}

	public static String getChinese() {
		try {
			return getChinese(random.nextInt(DEFAULT_RANGE));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String getChinese(long seed) throws Exception {
		String str = null;
		int highPos, lowPos;
		seed = new Date().getTime() + seed;
		Random random = new Random(seed);
		highPos = (176 + Math.abs(random.nextInt(39)));
		lowPos = 161 + Math.abs(random.nextInt(93));

		byte[] b = new byte[2];
		b[0] = (new Integer(highPos)).byteValue();
		b[1] = (new Integer(lowPos)).byteValue();
		str = new String(b, "GB2312");
		return new String(str.getBytes(), "utf-8");
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(getRandomString());
		System.out.println(getRandomString(Locale.ENGLISH));
	}

}
